package com.ple.app.importdata;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ple.app.jzsf.R;
import com.ple.app.sevlet.DbOption;
import com.ple.app.sevlet.GetFromServer;
import com.ple.app.sevlet.GetIdList;
import com.ple.app.sevlet.JsonTools;
import com.ple.app.sevlet.NetConnect;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class InputSeed_Activity extends Activity {


    private Spinner chooseseedtype;

    private ImageButton imageButton;
    /**
     * 种子信息
     */
    private ListView listView;
    private int operation_id=0;//删除修改是的ID
    private String seed_typevalue;//种子种类
    private ArrayAdapter<String> type_adapter;//种子种类转换适配器
    private String[] conlm=new String[]{"ID","name","tkw","seedrate","crop"};
    private  static  final String[] seedtype={"所有","玉米","小麦","大豆","水稻" };
    private  static  final String[] dialog_seedtype={"玉米","小麦","大豆","水稻" };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_seed);
        initData();
        /**
         * 种类适配器
         */
        chooseseedtype= (Spinner) findViewById(R.id.chooseseed);
        type_adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,seedtype);
        chooseseedtype.setAdapter(type_adapter);
        /**
         * 选择种子分类展示
         */
        chooseseedtype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

                    seed_typevalue = seedtype[position];
                    String[] args = new String[]{seed_typevalue};
                    MyopenHelper myopenhelper = new MyopenHelper(InputSeed_Activity.this, "seed.db", null, 1);
                    SQLiteDatabase db = myopenhelper.getReadableDatabase();
                    Cursor curor;
                    if (position != 0) {
                        curor = db.query("seed", conlm, "crop=?", args, null, null, null, null);
                    }//if
                    else {
                        curor = db.query("seed", conlm, null, null, null, null, null, null);
                    }
                    while (curor.moveToNext()) {
                        Map<String, Object> item = new HashMap<String, Object>();
                        String id1 = curor.getString(0);
                        String name = curor.getString(1);
                        String other1 = curor.getString(2);
                        String other2 = curor.getString(3);
                        item.put("ID", id1);
                        item.put("name", name);
                        item.put("tkw", other1);
                        item.put("seedrate", other2);
                        list.add(item);
                    }
                    db.close();
                    curor.close();


                    SimpleAdapter adapter = new SimpleAdapter(InputSeed_Activity.this, list, R.layout.seed_item, new String[]{"ID", "name", "tkw", "seedrate"},
                            new int[]{R.id.ID, R.id.Name, R.id.other1, R.id.other2});
                    listView = (ListView) findViewById(R.id.seed_data); //(ListView) findViewById(R.id.seed_datagrid);
                    listView.setAdapter(adapter);

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        /**
         * 添加信息
         */
        imageButton= (ImageButton) findViewById(R.id.toleft);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showPopupWindow(v);
                LayoutInflater a=LayoutInflater.from(InputSeed_Activity.this);
                final View dialogview=a.inflate(R.layout.add_seedata,null);
                final Spinner seed_type= (Spinner) dialogview.findViewById(R.id.seed_type);
                final EditText ID=(EditText) dialogview.findViewById(R.id.seed_id);
                final EditText name1=(EditText) dialogview.findViewById(R.id.seed_name);
                final EditText other11=(EditText) dialogview.findViewById(R.id.seed_other1);
                final EditText other12=(EditText) dialogview.findViewById(R.id.seed_other2);
                type_adapter=new ArrayAdapter<String>(InputSeed_Activity.this,android.R.layout.simple_spinner_item,dialog_seedtype);
                seed_type.setAdapter(type_adapter);
                seed_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        //获得下拉框中的值
                        seed_typevalue=dialog_seedtype[position];
                    }
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {}
                });//Spinner
                //生成ID
                MyopenHelper myopenhelper1=new MyopenHelper(InputSeed_Activity.this,"seed.db",null,1);
                SQLiteDatabase db1=myopenhelper1.getReadableDatabase();
                Cursor curor_getid=db1.query("seed",conlm,null,null,null,null,null,null);
                String curor_id ="0";
                if(curor_getid.getCount()!=0&&curor_getid.moveToLast())curor_id=curor_getid.getString(0);
                db1.close();
                curor_getid.close();
                int id=1+Integer.valueOf(curor_id);
                ID.setText(String.valueOf(id));
                //添加数据
                add(dialogview,ID,name1,other11,other12);
            }
        });
    }//oncreat

    /**
     * chushihua
     */
    private void initData()  {

        listView = (ListView) findViewById(R.id.seed_data);
        //seeddatatolistview();
        if(NetConnect.isNetworkAvailable(InputSeed_Activity.this))update();
        else{
            Toast.makeText(getApplicationContext(),"没有网络连接",Toast.LENGTH_LONG).show();
            seeddatatolistview();
        }
        /**
         *  选中状态List view的Item
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,String> getmap= (HashMap<String, String>) listView.getItemAtPosition(position);
                String ID=getmap.get("ID");
                operation_id=Integer.valueOf(ID);
                showPopupWindow(view);
                //Toast.makeText(getApplicationContext(),ID,Toast.LENGTH_LONG).show();
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //Intent intent=new Intent(InputSeed_Activity.this,InfomationActivity.class);
                //startActivity(intent);
                return false;//想长按时不执行单机事件，则设置为true；
            }
        });}
    /**
     * popwindow
     */
    private void showPopupWindow(View view){
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_sqlopreation, null);
        // 设置按钮的点击事件
         TextView see_more= (TextView) contentView.findViewById(R.id.see_more);
        see_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(),"请选择待删除的种子信息",Toast.LENGTH_LONG).show();
                Intent intent=new Intent(InputSeed_Activity.this,InfomationActivity.class);
                startActivity(intent);

            }
        });//plus
        /**
         * delet
         */
        TextView delet= (TextView) contentView.findViewById(R.id.delet_information);
        delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delet();
            }
        });
        final PopupWindow popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT
               , WindowManager.LayoutParams.WRAP_CONTENT , true);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        // 设置好参数之后再show
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.data_background));
       // popupWindow.showAtLocation(view, Gravity.RIGHT,0,0);
        popupWindow.showAsDropDown(view,300,-175);
    }
    /**
     * 添加种子信息
     */
    private void add(final View dialogview ,final EditText ID,final EditText name1,final EditText other11,final EditText other12)
    {

        String title;
        title="添加种子信息";

        new AlertDialog.Builder(InputSeed_Activity.this).setTitle(title)
                .setView(dialogview)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = name1.getText().toString();
                        String other1 = other11.getText().toString();
                        String other2 = other12.getText().toString();

                            if (name.equals("") || other1.equals("")) {
                                Toast.makeText(getApplicationContext(), "种子信息不完整，添加失败！", Toast.LENGTH_LONG).show();
                            } else {
                                //String[] conlm=new String[]{"ID","name","other1","other2","wrap"};
                                MyopenHelper myopenhelper = new MyopenHelper(InputSeed_Activity.this, "seed.db", null, 1);
                                SQLiteDatabase db = myopenhelper.getReadableDatabase();
                                int id = Integer.valueOf(ID.getText().toString());
                                ContentValues values = new ContentValues();
                                values.put("ID", id);
                                values.put("name", name);
                                values.put("tkw", other1);
                                values.put("seedrate", other2);
                                values.put("crop", seed_typevalue);
                                db.insert("seed", null, values);
                                Cursor curor = db.query("seed", conlm, null, null, null, null, null, null);
                                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                                while (curor.moveToNext()) {
                                    Map<String, Object> item = new HashMap<String, Object>();
                                    String id11 = curor.getString(0);
                                    String name11 = curor.getString(1);
                                    String other111 = curor.getString(2);
                                    String other121 = curor.getString(3);
                                    item.put("ID", id11);
                                    item.put("name", name11);
                                    item.put("tkw", other111);
                                    item.put("seedrate", other121);
                                    list.add(item);
                                }
                                SimpleAdapter adapter = new SimpleAdapter(InputSeed_Activity.this,
                                        list, R.layout.seed_item, new String[]{"ID", "name", "tkw", "seedrate"},
                                        new int[]{R.id.ID, R.id.Name, R.id.other1, R.id.other2});
                                //listView = (ListView) findViewById(R.id.seed_data); //(ListView) findViewById(R.id.seed_datagrid);
                                listView.setAdapter(adapter);
                                db.close();
                                curor.close();
                            }
                    }
                }).setNegativeButton("取消", null).create().show();


    }
    /**
     * 删出数据
     */
    private void delet(){
        if(operation_id==0){
          Toast.makeText(getApplicationContext(),"请选择待删除的种子信息",Toast.LENGTH_LONG).show();

        }
        else{
            new AlertDialog.Builder(InputSeed_Activity.this).setTitle("系统提示")
                    .setMessage("确认删除此条信息？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                                String[] args=new String[]{String.valueOf(operation_id)};
                                MyopenHelper myopenhelper=new MyopenHelper(InputSeed_Activity.this,"seed.db",null,1);
                                SQLiteDatabase db=myopenhelper.getReadableDatabase();
                                db.delete("seed","ID=?",args);
                                DbOption.adddeleid(db,"seed",operation_id);//需要删除的数据id给服务端
                                db.close();
                                seeddatatolistview();
                                Toast.makeText(getApplicationContext(),"已删除种子信息",Toast.LENGTH_LONG).show();


                        }
                    }).setNegativeButton("取消",null).create().show();}
    }
    /**
     * 更新种子Listview
     */
    private void seeddatatolistview(){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //String[] conlm=new String[]{"ID","name","other1","other2","wrap"};
        MyopenHelper myopenhelper=new MyopenHelper(InputSeed_Activity.this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
        Cursor curor=db.query("seed",conlm,null,null,null,null,null,null);
        while(curor.moveToNext()){
            Map<String, Object> item = new HashMap<String, Object>();
            String id=curor.getString(0);
            String name=curor.getString(1);
            String other1=curor.getString(2);
            String other2=curor.getString(3);
            item.put("ID", id);
            item.put("name", name);
            item.put("tkw", other1);
            item.put("seedrate", other2);
            list.add(item);}
        curor.close();
        db.close();
        SimpleAdapter adapter = new SimpleAdapter(InputSeed_Activity.this, list, R.layout.seed_item, new String[]{"ID", "name", "tkw", "seedrate"},
                new int[]{R.id.ID, R.id.Name, R.id.other1, R.id.other2});
        listView.setAdapter(adapter);

    }
    /**
     * 从服务端获得数据
     */
    private void update(){
        final Handler myHandler=new Handler() {
            @Override
            public void handleMessage(Message msg) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                String rponse= (String) msg.obj;

                if(rponse.isEmpty()){Toast.makeText(getApplicationContext(),"网络连接异常",Toast.LENGTH_LONG).show();}
                else if(rponse.equals("1")){Toast.makeText(getApplicationContext(),"同步完成",Toast.LENGTH_LONG).show();}
                else{

                   list= JsonTools.getListmap("data",rponse);//获得服务器传来的数据
                   int size=list.size();
                    MyopenHelper myopenhelper = new MyopenHelper(InputSeed_Activity.this, "seed.db", null, 1);
                    SQLiteDatabase db = myopenhelper.getReadableDatabase();
                    /**
                     * 如果服务端删除成功，清楚缓存
                     */
                    db.delete("delete_id",null,null);
                    /**
                     * 同步到本地
                     */
                for(int i=0;i<size;i++){
                Map<String, Object> item = new HashMap<String, Object>();
                item= list.get(i);
                String id= String.valueOf(item.get("id"));
                String name= String.valueOf(item.get("name"));
                String twk= String.valueOf(item.get("tkw"));
                String seddlingrate= String.valueOf(item.get("seedlingrate"));
                String crop= String.valueOf(item.get("crop"));

                ContentValues values = new ContentValues();
                values.put("ID", id);
                values.put("name", name);
                values.put("tkw", twk);
                values.put("seedrate", seddlingrate);
                values.put("crop", crop);
                db.insert("seed", null, values);
                }// while(iterator.hasNext())
                db.close();
                seeddatatolistview();

                    /**
                     * 传数据给服务器
                     */
                   final String jsonstring=GetIdList.DBofseedToServer(InputSeed_Activity.this,rponse);
                    if(jsonstring.equals("0")){}
                    else{
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            GetFromServer getfromserver=new GetFromServer();
                            getfromserver.postDB(jsonstring,getfromserver.seed_url);
                        }
                    }).start();}
                    Toast.makeText(getApplicationContext(),"同步完成",Toast.LENGTH_LONG).show();
                }//else

            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonstring=GetIdList.getAllidFromTB(InputSeed_Activity.this,"seed");
                String jsondeleteid=GetIdList.DBofdeleteToServer(InputSeed_Activity.this);
                GetFromServer getfromserver=new GetFromServer();
                String result=getfromserver.dopost(jsonstring,jsondeleteid,getfromserver.seed_url);
                Message msg=new Message();
                msg.obj=result;
                myHandler.sendMessage(msg);
            }
        }).start();
    }
}
